// m_cmsuser.go
package bmodel

import (
	"fmt"

	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
)

/*
 * check if cmsuser occurs
 * para: username string, password string
 * return error
 */
func CmsCheckuserIsExist(username, password string) error {
	if len(username) == 0 || len(password) == 0 { //should judge whether it is empty, otherwise where expression will become "select *"
		return fmt.Errorf(ERROR_EMPTY_CMSUSER_USERNAME_PASSWORD)
	} else {
		db, dberr := gorm.Open("mysql", DB_CONNECT_STR)
		defer db.Close()
		if dberr != nil {
			return fmt.Errorf(ERROR_CANNOT_OPEN_DB)
		}
		var cmsusers []Cmsuser
		db.Where(&Cmsuser{Username: username, Password: password}).Find(&cmsusers)
		if len(cmsusers) > 0 {
			return nil
		} else {
			return fmt.Errorf(ERROR_CMSUSER_NOTFOUND)
		}
	}
}

/*
 * add cmsuser, used only in offline golang run
 * para: username string, password string, needmd5 bool
 * return bool, error
 */
func AddCmsuser(username, password string, needmd5 bool) (bool, error) {
	db, dberr := gorm.Open("mysql", DB_CONNECT_STR)
	defer db.Close()
	if dberr != nil {
		panic(dberr)
		return false, fmt.Errorf(ERROR_CANNOT_OPEN_DB)
	}
	var cmsusers []Cmsuser
	db.Where(&Cmsuser{Username: username}).Find(&cmsusers)
	if len(cmsusers) > 0 {
		return false, fmt.Errorf(ERROR_CMSUSER_HAS_BEEN_CREATED)
	} else {
		if needmd5 {
			if errc := db.Create(&Cmsuser{Username: username, Password: Md5encode(password)}).Error; errc != nil {
				return false, fmt.Errorf(ERROR_CMSUSER_CANNOT_BE_CREATED)
			} else {
				return true, nil
			}
		} else {
			if errc := db.Create(&Cmsuser{Username: username, Password: password}).Error; errc != nil {
				return false, fmt.Errorf(ERROR_CMSUSER_CANNOT_BE_CREATED)
			} else {
				return true, nil
			}
		}
	}
}
